<script lang="ts">
  import { Modal } from "@skeletonlabs/skeleton-svelte";
  import type { Store as ToastStore } from "@zag-js/toast";
  import { getContext } from "svelte";
  import { X } from "lucide-svelte";
  import { userStore } from "$lib/stores/user.svelte";
  import { request } from "$lib/utils/request";
  import { update_basic } from "$lib/api/user";

  const toast: ToastStore = getContext("toast");

  interface ModalProps {
    onClose: () => void;
  }

  let props: ModalProps = $props();

  let displayName = $state(userStore.userInfo?.basic_info.display_name ?? "");

  async function updateDisplayName() {
    await request(
      update_basic({
        session_id: userStore.userSession,
        basic_info: {
          display_name: displayName,
          logo_uri: userStore.userInfo?.basic_info.logo_uri ?? "",
        },
      })
    );
    if (userStore.userInfo != null) {
      userStore.userInfo.basic_info.display_name = displayName;
    }
    toast.create({
      title: "成功",
      description: "修改成功!",
      type: "success",
    });
    props.onClose();
  }
</script>

<Modal
  open={true}
  triggerBase="btn preset-tonal"
  contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl w-[500px]"
  backdropClasses="backdrop-blur-xs"
  backdropBase="backdrop-none"
  onOpenChange={(ev) => {
    if (!ev.open) {
      props.onClose();
    }
  }}
>
  {#snippet content()}
    <header class="flex justify-between">
      <h4 class="h4">修改昵称</h4>
      <button
        type="button"
        class="btn preset-ghost-primary-500"
        onclick={() => props.onClose()}
      >
        <X />
      </button>
    </header>
    <label class="label">
      <span class="label-text">昵称</span>
      <input
        class="input bg-surface-50-950 rounded-none"
        type="text"
        bind:value={displayName}
        placeholder="请输入昵称"
      />
    </label>
    <footer class="flex justify-end gap-4 mt-[20px]">
      <button
        type="button"
        class="btn preset-tonal"
        onclick={() => props.onClose()}>取消</button
      >
      <button
        type="button"
        class="btn preset-filled-primary-900-100"
        disabled={displayName.trim() == ""}
        onclick={() => {
          updateDisplayName();
        }}
      >
        修改
      </button>
    </footer>
  {/snippet}
</Modal>
